<template>
    <div>
      <h3>商品分类页面</h3>
       <Breadcrumb :breadcrumba="breadcrumba" :breadcrumbb="breadcrumbb"></Breadcrumb>
       <el-card>
           <el-row>
               <el-col>
                   <el-button type="primary" @click="addCategories">添加分类</el-button>
               </el-col>
           </el-row>

           <!-- 商品表格区 -->
            <!-- <el-table
                :data="cateList"
                style="width: 100%"
                row-key="cat_id"
                border
                lazy
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column
                type="index"
                width="50">
                </el-table-column>
                <el-table-column
                prop="cat_name"
                label="商品名称"
                width="180">
                </el-table-column>
                <el-table-column
                prop="cat_deleted"
                label="是否有效">
                </el-table-column>
                <el-table-column
                prop="cat_level"
                label="排序">
                </el-table-column>
                <el-table-column
                
                label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" @click="editr(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table> -->
             <!-- 需要下载一个插件 vue-table-with-tree-grid -->
             <tree-table
              :data="cateList"
              :columns="columns"
              :selection-type="false"
              :expand-type="false"
              :show-index="true"
              index-text="#"
              border
             >
             <!-- 是否有效 -->
              <template slot="isok" slot-scope="scope">
                  <i class="el-icon-success" v-if="!scope.row.cat_deleted" style="color :#67C23A"></i>
                  <i class="el-icon-error" v-else style="color :##F56C6C"></i>
              </template>

              <!-- 排序 作用域插槽-->
              <template slot="order" slot-scope="scope">
                 <el-tag v-if="scope.row.cat_level === 0">一级标签</el-tag>
                 <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级标签</el-tag>
                 <el-tag v-else type="warning">三级标签</el-tag>
              </template>

              <template slot="operation" slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" @click="editr(scope.row)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
              </template>
              </tree-table>

           <!-- 分页区 -->
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>

            <!-- 添加分类弹出框 -->
            <el-dialog
            title="添加分类"
            :visible.sync="dialogVisible"
            width="40%"
            @close="resetForm"
            >
            <!-- 添加新的分类 -->
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" >
                <el-form-item label="分类名称：" prop="cat_name">
                    <el-input v-model="ruleForm.cat_name"></el-input>
                </el-form-item>
                    <!-- props 指定 配置对象 的 对象行使的 :props="cascaderProps" :change-on-select="true" expand-trigger="hover"-->
                    <!-- props新版的 书写规范 看文档 -->
                 <el-form-item label="父级分类：">
                     <!-- v-model 对应的是 数组 -->
                   <el-cascader
                    v-model="selectedKeys"
                    :options="parentCatList"
                    @change="handleChange"
                    :props="{ expandTrigger: 'hover',
                    checkStrictly: true,
                    value:cascaderProps.value,
                    label:cascaderProps.label,
                    children:cascaderProps.children}"
                    clearable
                    size="medium"
                    ></el-cascader>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addCategories2">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 编辑分类信息 -->
            <el-dialog
            title="编辑分类信息"
            :visible.sync="editdialogVisible"
            width="40%"
            @close="editresetForm"
            >
            <span>编辑</span>
            <el-form :model="categoriesById" :rules="rules" ref="categoriesByIdForm" label-width="100px" >
                <el-form-item label="分类名称：" prop="cat_name">
                    <el-input v-model="categoriesById.cat_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editdialogById">确 定</el-button>
            </span>
            </el-dialog>
       </el-card>
    </div>
</template>

<script>
import Breadcrumb from "../../components/Breadcrumb"
import {getGoodsList,addCategories,findCategories,editCategories,delCategories} from "../../api/goods"
    export default {
        components:{
            Breadcrumb
        },
        data(){
            return{
                breadcrumba:'',
                breadcrumbb:'',
                cateList:[],
                queryInfo:{
                    type:3,
                    pagenum:1,
                    pagesize:5
                },
                total:0,
                // 为table指定标题 模板列
                columns:[
                    {
                        label:"分类名称",
                        prop:'cat_name'
                    },
                    {
                        label:"是否有效",
                        // prop:'cat_name'
                        type:"template",
                        // 表示当前列 使用的 模板名称
                        template:'isok'
                    },
                    {
                        label:"排序",
                        type:"template",
                        // 表示当前列 使用的 模板名称
                        template:'order'
                    },
                    {
                        label:"操作",
                        type:"template",
                        template:"operation"
                    }
                ],
                dialogVisible:false,
                ruleForm:{
                    cat_name:"",
                    // 父级分类id
                    cat_pid:0,
                    cat_level:0
                },
                rules: {
                    cat_name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' },
                        { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
                    ],
                },
                
                parentCatList:[],
                // 指定级联 选择器 的配置对象  分别是 值 名称 父子通过什么进行嵌套的
                cascaderProps:{
                    value:'cat_id',
                    label:'cat_name',
                    children:'children'
                },
                // 选中的父级分类的 id 数组
                selectedKeys:[],
                // 通过id 获取和 编辑 分类信息
                categoriesById:{

                },
                editdialogVisible:false
            }
        },
        created(){
            this.breadcrumba=sessionStorage.getItem('breadcrumba')
            this.breadcrumbb=sessionStorage.getItem('breadcrumbb')
            this.getGoodsList()
        },
        methods:{
            handleSizeChange(newpagesize) {
                // console.log(`每页 ${val} 条`);
                this.queryInfo.pagesize = newpagesize
                this.getGoodsList()
            },
            handleCurrentChange(newpagenum) {
                // console.log(`当前页: ${val}`);
                 this.queryInfo.pagenum = newpagenum
                 this.getGoodsList()
            },
            async getGoodsList(){
                let {data:res} = await getGoodsList(this.queryInfo)
                console.log(res,"所有商品的列表");
                if(res.meta.status !== 200){
                    return this.$message.error("获取商品列表失败")
                }

                this.cateList = res.data.result
                this.total = res.data.total
            },
            // 编辑 分类
            async editr(row){
                this.editdialogVisible = true
                // console.log(row,"ddd");
                let {data:res} = await findCategories({id:row.cat_id})
                // console.log(res,"查询分类");
                if(res.meta.status !== 200){
                    return this.$message.error('获取分类信息失败！')
                }

                this.categoriesById = res.data
            },
            //  删除分类
            del(row){

                this.$confirm('此操作将永久删除该该分类, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then( async () => {
                    // console.log(row,"kkk");
                let {data:res}  = await delCategories(row.cat_id)
                // console.log(res,"删除之后的返回值");

                if(res.meta.status !== 200){
                    return this.$message.error('删除分类失败！')
                }
               
                this.getGoodsList()
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
                });
            },
            addCategories(){
                // console.log(2);
                this.getParentCatList()
                this.dialogVisible = true
            },
            // 关闭时 需要都进行清空
            resetForm() {
                // this.$refs[formName].resetFields();
                this.ruleForm.cat_name = "",
                this.selectedKeys = [],
                this.ruleForm.cat_pid = 0,
                this.ruleForm.cat_level = 0
            },
            async getParentCatList(){
                let {data:res} = await getGoodsList({type:2})
                if(res.meta.status !== 200){
                    return this.$message,error("获取父级数据列表错误！")
                }
                // console.log(res,"获取的是父级二级的列表");
                this.parentCatList = res.data
            },
            // 联级 监听改变时间 发生改变 会执行这个函数
            handleChange() {
                console.log(this.selectedKeys,"改变之后数组的值");
                // selectedKeys 的长度 大于0  证明有父级  反之  则没有通过 数组的 长度 进行 判断与赋值
                if(this.selectedKeys.length > 0){
                    this.ruleForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
                    // 当前分类的等级 赋值
                    this.ruleForm.cat_level = this.selectedKeys.length
                }else{
                     this.ruleForm.cat_pid = 0
                     this.ruleForm.cat_level = 0
                }
            },
            // 点击按钮 添加新的分类
            async addCategories2(){
                // console.log(this.ruleForm,"点击确定之后的form表单内容");
                let {data:res} = await addCategories(this.ruleForm)
                // console.log(res,"添加之后的返回的值");
                if(res.meta.status !== 201){
                    return this.$message.error("添加分类失败！")
                }
                
                this.$message.success("添加分类成功！")
                this.dialogVisible = false
                this.getGoodsList()

            },
            editresetForm(){
                // console.log("关闭弹出框");
                this.categoriesById = {}
            },
            async editdialogById(){
                // console.log(this.categoriesById.cat_name,"编辑分类提交的Info");
                let {data:res} = await editCategories(this.categoriesById.cat_id,{cat_name:this.categoriesById.cat_name})
                if(res.meta.status !== 200){
                    return this.$message.error('更新分类失败！')
                }
                // console.log(res,"编辑之后的返回值");
                this.$message.success('更新分类成功！')
                this.getGoodsList()
                this.editdialogVisible = false

            }
        }
    }
</script>

<style scoped>
    .el-card{
        margin-top: 10px;
    }
    .el-button{
        margin-bottom: 10px;
    }
    .el-pagination{
        margin-top: 10px;
    }
</style>